//
//  Budle+language.swift
//  Exchange
//
//  Created by rui on 2018/4/23.
//  Copyright © 2018年 common. All rights reserved.
//

import Foundation

var BundleExKey = "BundleExKey"
var BundleChatKey = "BundleChatKey"


class BundleEx: Bundle {
    @objc override func localizedString(forKey key: String, value: String?, table tableName: String?) -> String {
        if let bundle = objc_getAssociatedObject(self, &BundleExKey) as? Bundle  {
           return bundle.localizedString(forKey: key, value: value, table: tableName)
        }
        return super.localizedString(forKey: key, value: value, table: tableName)
    }
}

class BundleChat: Bundle {
    @objc override func localizedString(forKey key: String, value: String?, table tableName: String?) -> String {
        if let bundle = objc_getAssociatedObject(self, &BundleChatKey) as? Bundle  {
            return bundle.localizedString(forKey: key, value: value, table: tableName)
        }
        return super.localizedString(forKey: key, value: value, table: tableName)
    }
}



extension Bundle {
    
    private static let once: Int = {
        object_setClass(Bundle.main, BundleEx.self)
        if let chatPath = Bundle.main.path(forResource: "ZDCChatStrings", ofType: "bundle"),let chatBundle = Bundle(path: chatPath) {
            object_setClass(chatBundle, BundleChat.self)
        }
        return 1
    }()
    static func setLanguage(_ language: String) {
        let _ = Bundle.once
        if let path = Bundle.main.path(forResource: language, ofType: "lproj") {
            let bundle = Bundle(path: path)
            objc_setAssociatedObject(Bundle.main, &BundleExKey, bundle, .OBJC_ASSOCIATION_RETAIN)
        }
        
        if let chatPath = Bundle.main.path(forResource: "ZDCChatStrings", ofType: "bundle"),let chatBundle = Bundle(path: chatPath),let path = chatBundle.path(forResource: language, ofType: "lproj") {
            let lg = Bundle(path: path)
             objc_setAssociatedObject(chatBundle, &BundleChatKey, lg, .OBJC_ASSOCIATION_RETAIN)
        }
    }

}
